package com.photoeditor.demo.ui.widget.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.util.LongSparseArray;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;

import com.common.base.ComponentContext;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.model.image.gl.ApiHelper;
import com.photoeditor.demo.model.image.gl.DecoderLoader;
import com.photoeditor.demo.model.image.gl.Future;
import com.photoeditor.demo.model.image.gl.ThreadPool;
import com.photoeditor.demo.model.image.util.Utils;
import com.photoeditor.demo.util.gallery.util.GalleryBitmapPool;


/**
 * 基于Ａndroid原生相册的算法实现的分块解析图片的Ｖiew
 * 用完需要调用recycle
 * 使用了GalleryBitmapPool重复利用已经申请的内存空间
 */
public class TileImageView extends View implements View.OnTouchListener {

    private boolean mIsInit;

    /**
     * 图片最开始显示的SourceRect  未旋转前
     */
    private Rect mBitmapDefaultRect = new Rect();

    /**
     * 图片最开始显示的SourceRect  未旋转前
     */
    private RectF mViewDefaultRect = new RectF();

    /**
     * 当前图片显示的Rect  未旋转前
     */
    private RectF mViewTargetRect = new RectF();

    private RectF mCacheRect = new RectF();

    private RectF mViewCacheRect = new RectF();

    /**
     * 顶宽  还是  顶高
     */
    private boolean mFlag = false;

    private static final float MAX_SCALE = 4f;

    private static final float MIN_SCALE = 0.125f;

    private float mDefaultScale;

    private PreViewBitmap mScreen;

    private Matrix mCacheMatrix;

    private Matrix mSupportMatrix;

    private final static int MSG_REFRESH = 1;

    private final static int MSG_DECODED_BITMAP = 2;


    /**
     * 原图的长款
     */
    private int mImageHeight;
    private int mImageWidth;


    private int mLevel = 0;

    protected int mLevelCount;  // cache the value of mScaledBitmaps.length

    private int mOffsetX;
    private int mOffsetY;

    // Temp variables to avoid memory allocation
    private final Rect mTileRange = new Rect();
    private final Rect mActiveRange[] = {new Rect(), new Rect()};

    private final TileBitmapQueue mRecycledQueue = new TileBitmapQueue();
    private final TileBitmapQueue mUploadQueue = new TileBitmapQueue();
    private final TileBitmapQueue mDecodeQueue = new TileBitmapQueue();

    private final LongSparseArray<TileBitmap> mActiveTiles = new LongSparseArray<TileBitmap>();

    public static int sTileSize = 0;

    private Future<?> mTileDecoder;

    private int mRotation;
    protected int mCenterX = -1;
    protected int mCenterY = -1;
    private float mScale = 0f;

    private float mCacheScale;

    private final Rect mSourceRect = new Rect();
    private final RectF mTargetRect = new RectF();


    private Paint mPaint;

    /**
     * 用于fling
     */
    private final int MAX_VALUE = 20000;

    private final int MIN_VALUE = 10000;

    /**
     * 缓存doubleTap时 是否动画
     */
    private boolean mIsAnimation = false;

    private boolean mDontNeedTile = true;

    private PreViewBitmap.DecodeListener mListener = new PreViewBitmap.DecodeListener() {

        @Override
        public void onDecodeOver(Bitmap bitmap, int w, int h, BitmapRegionDecoder decoder) {
            Message msg = Message.obtain(mHandler, MSG_DECODED_BITMAP, decoder);
            msg.arg1 = w;
            msg.arg2 = h;
            Bundle b = new Bundle();
            b.putParcelable("bitmap", bitmap);
            msg.setData(b);
            mHandler.sendMessage(msg);
        }
    };

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            if (msg.what == MSG_REFRESH) {
                invalidate();
            } else if (msg.what == MSG_DECODED_BITMAP) {
                BitmapRegionDecoder decoder = (BitmapRegionDecoder) msg.obj;
                Bitmap bitmap = msg.getData().getParcelable("bitmap");
                if (bitmap == null) {
                    if (mDecodeListener != null) {
                        mDecodeListener.onDecodeOver(TileImageView.this, false);
                    }
                } else {
                    mScreen.setDecoder(decoder);
                    mScreen.setBitmap(bitmap);
                    mImageWidth = msg.arg1;
                    mImageHeight = msg.arg2;
                    if (getWidth() != 0 && getHeight() != 0) {
                        initBitmapAndShow(bitmap);
                    }
                }
            }
        }

        ;
    };

    private MyGestureListener mGestureListener;
    private GestureRecognizer mGestureRecognizer;

    private AnimationHelper mAnimationHelper;

    private OnDecodeListener mDecodeListener;

    private OnViewTapListener mTapViewListener;

    public TileImageView(Context context) {
        this(context, null);
    }

    public TileImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            if (!isInit()) {
                if (getWidth() != 0 && getHeight() != 0) {
                    Bitmap bitmap = mScreen.getScreenBitmap();
                    if (bitmap != null) {
                        initBitmapAndShow(bitmap);
                    }
                }
                return;
            }

            if (mCenterX == -1) {
                mCenterX = getWidth() / 2;
                mCenterY = getHeight() / 2;
            }
        }
        layoutTiles(mCenterX, mCenterY, mScale, mRotation);
    }

    private void init() {
        setWillNotDraw(false);
        setDrawingCacheEnabled(true);
        mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
        /**
         * 这个必须设置不然在某些机型上会闪烁
         */
//		setLayerType(View.LAYER_TYPE_HARDWARE, null);

        setBackgroundColor(Color.TRANSPARENT);

        mCacheMatrix = new Matrix();
        mSupportMatrix = new Matrix();
        if (sTileSize == 0) {
            if (Utils.isHighResolution(getContext())) {
                sTileSize = 512;
            } else {
                sTileSize = 256;
            }
        }
        setOnTouchListener(this);
        mGestureListener = new MyGestureListener();
        mGestureRecognizer = new GestureRecognizer(getContext(), mGestureListener);
        mAnimationHelper = new AnimationHelper(getContext());
    }

    /**
     * @param bitmap
     */
    private void initBitmapAndShow(Bitmap bitmap) {
        if (isNeedRotation(mRotation)) {
            int iw = mImageHeight;
            int ih = mImageWidth;

            float screenScale = getFiterMatrix(bitmap, mRotation);
            int bw = bitmap.getHeight();
            int bh = bitmap.getWidth();

            mLevelCount = calculateLevelCount(iw, bw);
            float bitmapScale = Math.max(bh * 1.0f / ih, bw * 1.0f / iw);
            mDefaultScale = bitmapScale * screenScale;
            setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mDefaultScale);
        } else {
            float screenScale = getFiterMatrix(bitmap, mRotation);
            mLevelCount = calculateLevelCount(mImageWidth, bitmap.getWidth());

            float bitmapScale = Math.max(bitmap.getHeight() * 1.0f / mImageHeight, bitmap.getWidth() * 1.0f / mImageWidth);
            mDefaultScale = bitmapScale * screenScale;
            setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mDefaultScale);
        }
        mIsInit = true;
        refresh();
        if (mDecodeListener != null) {
            mDecodeListener.onDecodeOver(this, true);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isInit()) return;
        if (mRotation != 0) {
            canvas.save();
            int centerX = getWidth() / 2, centerY = getHeight() / 2;
            canvas.translate(centerX, centerY);
            canvas.rotate(mRotation, 0, 0);
            canvas.translate(-centerX, -centerY);
        }
        int level = mLevel;
        if (mLevelCount != 0 && level != mLevelCount && !mIsAnimation && !mDontNeedTile) {
            int size = (sTileSize << level);
            float length = size * mScale;
            Rect r = mTileRange;

            mScreen.draw(canvas, mBitmapDefaultRect, mViewTargetRect);

            for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
                float y = mOffsetY + i * length;
                for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
                    float x = mOffsetX + j * length;
                    drawTile(canvas, tx, ty, level, x, y, length);
                }
            }
        } else if (mScreen != null) {
            mScreen.draw(canvas, mBitmapDefaultRect, mViewTargetRect);
        }
        if (mRotation != 0) {
            canvas.restore();
        }

        if (!mAnimationHelper.isFinished()) {//动画未被终止
            AnimationHelper.Point p = mAnimationHelper.getNextValue();
            if (p != null) {//需要更新画面
                if (mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE) {
                    if (mScale == p.x) {//已经到最后了  动画过程中foucusX 和 foucusY不变的  不用考虑
                        refresh();
                    } else {
                        doScale(p.x, p.foucusX, p.foucusY);
                    }
                } else if (mAnimationHelper.getMode() == AnimationHelper.MODE_FLING) {
                    doScroll(p.x, p.y);
                }
            } else {
                if (mIsAnimation) {
                    mIsAnimation = false;
                    refresh();
                }
            }
        } else {
            mAnimationHelper.setMode(AnimationHelper.MODE_NONE);
            if (mIsAnimation) {
                mIsAnimation = false;
                refresh();
            }
        }
    }

    /**
     * 将图片平移 dx dy
     *
     * @param dx
     * @param dy
     */
    private void doScroll(float dx, float dy) {
        float mTranslateX = dx;
        float mTranslateY = dy;

        if (mRotation != 0) {
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
        } else {
            mCacheRect.set(mViewTargetRect);
        }

        /**
         * 一些特殊情况的处理
         */
        if (mCacheRect.width() <= getWidth()) {
            mTranslateX = 0f;
        }

        if (mCacheRect.height() <= getHeight()) {
            mTranslateY = 0f;
        }

        if (mTranslateY == 0f && mTranslateX == 0f) {//已经不用平移了
            mAnimationHelper.foreFinish();
            refresh();
        } else {
            boolean flagX = false;
            boolean flagY = false;
            if (mCacheRect.height() > getHeight()) {
                if (mCacheRect.top + mTranslateY > 0f) {
                    mTranslateY = -mCacheRect.top;
                    flagY = true;
                } else if (mCacheRect.bottom + mTranslateY < getHeight()) {
                    mTranslateY = getHeight() - mCacheRect.bottom;
                    flagY = true;
                }
            }
            if (mCacheRect.width() > getWidth()) {
                if (mCacheRect.left + mTranslateX > 0f) {
                    mTranslateX = -mCacheRect.left;
                    flagX = true;
                } else if (mCacheRect.right + mTranslateX < getWidth()) {
                    mTranslateX = getWidth() - mCacheRect.right;
                    flagX = true;
                }
            }
            if (mRotation == 90) {
                float cache = mTranslateX;
                mTranslateX = mTranslateY;
                mTranslateY = -cache;
            } else if (mRotation == 180) {
                mTranslateX = -mTranslateX;
                mTranslateY = -mTranslateY;
            } else if (mRotation == 270) {
                float cache = mTranslateX;
                mTranslateX = -mTranslateY;
                mTranslateY = cache;
            }
            mViewTargetRect.offset(mTranslateX, mTranslateY);
            if (mRotation != 0) {
                mCacheMatrix.reset();
                mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
                mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
                setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mScale);
            } else {
                setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mScale);
            }

            if (flagX && flagY) {//已经是极限了 不需要做动画了
                mAnimationHelper.foreFinish();
            }
        }
    }

    /**
     * 图片以foucusX  foucusY 为中心  缩放scale
     * 这个方法只用于doubleTap的动画
     * 每次都会初始化掉 mViewTargetRect 为 mViewDefaultRect
     *
     * @param scale
     * @param foucusX
     * @param foucusY
     */
    private void doScale(float scale, float foucusX, float foucusY) {
        mIsAnimation = true;
        mCacheScale = scale;
        float currentScale = mCacheScale / mDefaultScale;
        mViewTargetRect.set(mViewDefaultRect);
        mCacheMatrix.reset();
        mCacheMatrix.setScale(currentScale, currentScale, foucusX, foucusY);
        mCacheMatrix.mapRect(mViewTargetRect);

        /**
         * 计算合适的偏移量
         */
        ensureRect();

        if (mRotation != 0) {
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
            setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mCacheScale);
        } else {
            setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mCacheScale);
        }
    }

    // Draw the tile to a square at canvas that locates at (x, y) and
    // has a side length of length.
    public void drawTile(Canvas canvas,
                         int tx, int ty, int level, float x, float y, float length) {
        Rect source = mSourceRect;
        RectF target = mTargetRect;
        target.set(x, y, x + length, y + length);
        source.set(0, 0, sTileSize, sTileSize);

        TileBitmap tile = getTile(tx, ty, level);
        if (tile != null) {
            if (tile.mStatus != TileBitmap.STATE_DECODE_FAIL) {
                queueForDecode(tile);
            }
            if (drawTile(tile, canvas, source, target)) return;
        }
//        if (mScreen != null) {
//            int size = sTileSize << level;
//            float scaleX = (float) mScreen.getWidth() / mImageWidth;
//            float scaleY = (float) mScreen.getHeight() / mImageHeight;
//            source.set((int)(tx * scaleX + 0.5f), (int)(ty * scaleY + 0.5f), (int)((tx + size) * scaleX + 0.5f),
//            		(int)(((ty + size) * scaleY) + 0.5f));
//            mScreen.draw(canvas, source, target);
//        }
    }

    static boolean drawTile(
            TileBitmap tile, Canvas canvas, Rect source, RectF target) {
        while (true) {
            if (tile.mTiledBitmap != null) {
                tile.draw(canvas, source, target);
                return true;
            }
            // Parent can be divided to four quads and tile is one of the four.
            TileBitmap parent = tile.getParentTile();
            if (parent == null) return false;
            if (tile.mX == parent.mX) {
                source.left = Math.round(source.left / 2f);
                source.right = Math.round(source.right / 2f);
            } else {
                source.left = (int) ((sTileSize + source.left) / 2f + 0.5f);
                source.right = (int) ((sTileSize + source.right) / 2f + 0.5f);
            }
            if (tile.mY == parent.mY) {
                source.top = Math.round(source.top / 2f);
                source.bottom = Math.round(source.bottom / 2f);
            } else {
                source.top = (int) ((sTileSize + source.top) / 2f + 0.5f);
                source.bottom = (int) ((sTileSize + source.bottom) / 2f + 0.5f);
            }
            tile = parent;
        }
    }

    synchronized void queueForDecode(TileBitmap tile) {
        if (tile.mStatus == TileBitmap.STATE_ACTIVATED) {
            tile.mStatus = TileBitmap.STATE_IN_QUEUE;
            if (mDecodeQueue.push(tile)) notifyAll();
        }
    }

    /**
     * 设置图片
     *
     * @param path
     * @param degree
     */
    public void setBitmapPath(String path, int degree, DecoderLoader loader) {
        mRotation = degree;
        if (mScreen == null) {
            mScreen = new PreViewBitmap(path, mListener, loader);
        } else {
            mScreen.update(path);
//			refresh();
        }
        mIsInit = false;
    }

    /**
     * 回收所有的资源
     */
    public void recycle() {
        setWillNotDraw(true);
        mIsInit = false;
        mDecodeListener = null;
        mDontNeedTile = true;
        if (mTileDecoder != null) {
            mTileDecoder.cancel();
            mTileDecoder.get();
            mTileDecoder = null;
        }
        int n = mActiveTiles.size();
        for (int i = 0; i < n; i++) {
            TileBitmap texture = mActiveTiles.valueAt(i);
            texture.recycle();
        }
        mActiveTiles.clear();
        mTileRange.set(0, 0, 0, 0);

        synchronized (this) {
            mUploadQueue.clean();
            mDecodeQueue.clean();
            TileBitmap tile = mRecycledQueue.pop();
            while (tile != null) {
                tile.recycle();
                tile = mRecycledQueue.pop();
            }
            if (mScreen != null) {
                mScreen.recycle();
            }
        }
    }


    /**
     * 回去合适的缩放比例  得到初始的rect  以及矩阵
     *
     * @param bitmap
     */
    private float getFiterMatrix(Bitmap bitmap, int degree) {
        float vw = getWidth();
        float vh = getHeight();
        float bw = bitmap.getWidth();
        float bh = bitmap.getHeight();

        float top, left, scale;

        if (isNeedRotation(degree)) {
            float cache = bw;
            bw = bh;
            bh = cache;
        }

        if (bw / bh > vw / vh) {//顶着宽
            scale = vw / bw;

            float nbw = vw;
            bh = vw / bw * bh;
            bw = nbw;

            left = 0.0f;
            top = (vh - bh) / 2;

            mFlag = true;
        } else {//顶着高
            scale = vh / bh;

            float nbh = vh;
            bw = vh / bh * bw;
            bh = nbh;

            left = (vw - bw) / 2;
            top = 0.0f;

            mFlag = false;
        }
        mBitmapDefaultRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());

        RectF dst = new RectF(left, top, left + bw, top + bh);

        mSupportMatrix.reset();
        mSupportMatrix.preTranslate(vw / 2 - mBitmapDefaultRect.centerX(), vh / 2 - mBitmapDefaultRect.centerY());
        mSupportMatrix.postScale(scale, scale, dst.centerX(), dst.centerY());

        mViewDefaultRect.set(mBitmapDefaultRect);

        mSupportMatrix.mapRect(mViewDefaultRect);

        mViewTargetRect.set(mViewDefaultRect);

        return scale;
    }

    /**
     * 公共方法  用于判断是否需要交换宽高
     *
     * @param degree
     * @return
     */
    private boolean isNeedRotation(int degree) {
        if (degree == 90 || degree == 270) {
            return true;
        }
        return false;
    }


    private void getRange(Rect out,
                          int cX, int cY, int level, float scale, int rotation) {

        double radians = Math.toRadians(-rotation);
        double w = getWidth();
        double h = getHeight();

        double cos = Math.cos(radians);
        double sin = Math.sin(radians);
        int width = (int) Math.ceil(Math.max(
                Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
        int height = (int) Math.ceil(Math.max(
                Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));

        int left = (int) Math.floor(cX - width / (2f * scale));
        int top = (int) Math.floor(cY - height / (2f * scale));
        int right = (int) Math.ceil(left + width / scale);
        int bottom = (int) Math.ceil(top + height / scale);

        // align the rectangle to tile boundary
        int size = sTileSize << level;
        left = Math.max(0, size * (left / size));
        top = Math.max(0, size * (top / size));
        right = Math.min(mImageWidth, right);
        bottom = Math.min(mImageHeight, bottom);

        out.set(left, top, right, bottom);
    }

    private void getRange(Rect out, int cX, int cY, int level, int rotation) {
        getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
    }

    /**
     * 生成新的tiles
     *
     * @param centerX
     * @param centerY
     * @param scale
     * @param rotation
     */
    private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
        // The width and height of this view.
        int width = getWidth();
        int height = getHeight();

        // The tile levels we want to keep as texture is in the range
        // [fromLevel, endLevel).
        int fromLevel;
        int endLevel;

        // We want to use a texture larger than or equal to the display size.
        mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);

        // We want to keep one more tile level as texture in addition to what
        // we use for display. So it can be faster when the scale moves to the
        // next level. We choose a level closer to the current scale.
        if (mLevel != mLevelCount) {
            Rect range = mTileRange;
            getRange(range, centerX, centerY, mLevel, scale, rotation);
            mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
            mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
            fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
        } else {
            // Activate the tiles of the smallest two levels.
            fromLevel = mLevel - 2;
            mOffsetX = Math.round(width / 2f - centerX * scale);
            mOffsetY = Math.round(height / 2f - centerY * scale);
        }

        fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
        endLevel = Math.min(fromLevel + 2, mLevelCount);

        Rect range[] = mActiveRange;
        for (int i = fromLevel; i < endLevel; ++i) {
            getRange(range[i - fromLevel], centerX, centerY, i, rotation);
        }

        // If rotation is transient, don't update the tile.
        if (rotation % 90 != 0) return;

        synchronized (this) {
            mDecodeQueue.clean();
            mUploadQueue.clean();

            // Recycle unused tiles: if the level of the active tile is outside the
            // range [fromLevel, endLevel) or not in the visible range.
            int n = mActiveTiles.size();
            for (int i = 0; i < n; i++) {
                TileBitmap tile = mActiveTiles.valueAt(i);
                int level = tile.mTileLevel;
                if (level < fromLevel || level >= endLevel
                        || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
                    mActiveTiles.removeAt(i);
                    i--;
                    n--;
                    recycleTile(tile);
                }
            }
        }

        for (int i = fromLevel; i < endLevel; ++i) {
            int size = sTileSize << i;
            Rect r = range[i - fromLevel];
            for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
                for (int x = r.left, right = r.right; x < right; x += size) {
                    activateTile(x, y, i);
                }
            }
        }
        refresh();
    }

    synchronized void recycleTile(TileBitmap tile) {
        if (tile.mStatus == TileBitmap.STATE_DECODING) {
            tile.mStatus = TileBitmap.STATE_RECYCLING;
            return;
        }
        tile.mStatus = TileBitmap.STATE_RECYCLED;
        if (tile.mTiledBitmap != null) {
            GalleryBitmapPool.getInstance().put(tile.mTiledBitmap);
            tile.mTiledBitmap = null;
        }
        mRecycledQueue.push(tile);
    }

    private void activateTile(int x, int y, int level) {
        long key = makeTileKey(x, y, level);
        TileBitmap tile = mActiveTiles.get(key);
        if (tile != null) {
            if (tile.mStatus == TileBitmap.STATE_IN_QUEUE) {
                tile.mStatus = TileBitmap.STATE_ACTIVATED;
            }
            return;
        }
        tile = obtainTile(x, y, level);
        mActiveTiles.put(key, tile);
    }

    private synchronized TileBitmap obtainTile(int x, int y, int level) {
        TileBitmap tile = mRecycledQueue.pop();
        if (tile != null) {
            tile.mStatus = TileBitmap.STATE_ACTIVATED;
            tile.update(x, y, level);
            return tile;
        }
        return new TileBitmap(x, y, level);
    }

    private TileBitmap getTile(int x, int y, int level) {
        return mActiveTiles.get(makeTileKey(x, y, level));
    }

    private static long makeTileKey(int x, int y, int level) {
        long result = x;
        result = (result << 16) | y;
        result = (result << 16) | level;
        return result;
    }

    boolean decodeTile(TileBitmap tile) {
        synchronized (this) {
            if (tile.mStatus != TileBitmap.STATE_IN_QUEUE) return false;
            tile.mStatus = TileBitmap.STATE_DECODING;
        }
        boolean decodeComplete = tile.decode();
        synchronized (this) {
            if (tile.mStatus == TileBitmap.STATE_RECYCLING) {
                tile.mStatus = TileBitmap.STATE_RECYCLED;
                if (tile.mTiledBitmap != null) {
                    GalleryBitmapPool.getInstance().put(tile.mTiledBitmap);
                    tile.mTiledBitmap = null;
                }
                mRecycledQueue.push(tile);
                return false;
            }
            tile.mStatus = decodeComplete ? TileBitmap.STATE_DECODED : TileBitmap.STATE_DECODE_FAIL;
            return decodeComplete;
        }
    }

    private int calculateLevelCount(int iw, int bw) {
        return Math.max(0, Utils.ceilLog2(
                (float) iw / bw));
    }


    private Bitmap getTileWithoutReusingBitmap(
            int level, int x, int y, int tileSize) {
        int t = tileSize << level;
        Rect wantRegion = new Rect(x, y, x + t, y + t);

        BitmapRegionDecoder regionDecoder;
        Rect overlapRegion;

        synchronized (this) {
            regionDecoder = mScreen.mDecoder;
            if (regionDecoder == null) return null;
            overlapRegion = new Rect(0, 0, mImageWidth, mImageHeight);
            Utils.assertTrue(overlapRegion.intersect(wantRegion));
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.ARGB_8888;
        options.inPreferQualityOverSpeed = true;
        options.inSampleSize = (1 << level);
        Bitmap bitmap = null;

        // In CropImage, we may call the decodeRegion() concurrently.
        synchronized (regionDecoder) {
            bitmap = regionDecoder.decodeRegion(overlapRegion, options);
        }

        if (bitmap == null) {
        }

        if (wantRegion.equals(overlapRegion)) return bitmap;

        Bitmap result = Bitmap.createBitmap(tileSize, tileSize, Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(bitmap,
                (overlapRegion.left - wantRegion.left) >> level,
                (overlapRegion.top - wantRegion.top) >> level, null);
        return result;
    }

    /**
     * 获取某个位置某个等级的tile
     *
     * @param level
     * @param x
     * @param y
     * @param tileSize
     * @return
     */
    public Bitmap getTile(int level, int x, int y, int tileSize) {
        if (!ApiHelper.HAS_REUSING_BITMAP_IN_BITMAP_REGION_DECODER) {
            return getTileWithoutReusingBitmap(level, x, y, tileSize);
        }

        int t = tileSize << level;

        Rect wantRegion = new Rect(x, y, x + t, y + t);

        boolean needClear;
        BitmapRegionDecoder regionDecoder = null;

        synchronized (this) {
            regionDecoder = mScreen.mDecoder;
            if (regionDecoder == null) return null;

            // We need to clear a reused bitmap, if wantRegion is not fully
            // within the image.
            needClear = !new Rect(0, 0, mImageWidth, mImageHeight)
                    .contains(wantRegion);
        }

        Bitmap bitmap = GalleryBitmapPool.getInstance().get(tileSize, tileSize);
        if (bitmap != null) {
            if (needClear) bitmap.eraseColor(0);
        } else {
            bitmap = Bitmap.createBitmap(tileSize, tileSize, Config.ARGB_8888);
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.ARGB_8888;
        options.inPreferQualityOverSpeed = true;
        options.inSampleSize = (1 << level);
        options.inBitmap = bitmap;

        try {
            // In CropImage, we may call the decodeRegion() concurrently.
            synchronized (regionDecoder) {
                bitmap = regionDecoder.decodeRegion(wantRegion, options);
            }
        } finally {
            if (options.inBitmap != bitmap && options.inBitmap != null) {
                GalleryBitmapPool.getInstance().put(options.inBitmap);
                options.inBitmap = null;
            }
        }

        if (bitmap == null) {
        }
        return bitmap;
    }

    void queueForUpload(TileBitmap tile) {
        synchronized (this) {
            mUploadQueue.push(tile);
            if (mDecodeQueue.isEmpty()) refresh();
        }
    }


    public class TileBitmap implements TileSource {

        public static final int STATE_ACTIVATED = 0x01;
        public static final int STATE_IN_QUEUE = 0x02;
        public static final int STATE_DECODING = 0x04;
        public static final int STATE_DECODED = 0x08;
        public static final int STATE_DECODE_FAIL = 0x10;
        public static final int STATE_RECYCLING = 0x20;
        public static final int STATE_RECYCLED = 0x40;

        public Bitmap mTiledBitmap;

        public TileBitmap mNext;

        /**
         * mx my size是解析时的位置和大小
         */
        public int mX;

        public int mY;

        public int mWidth;

        public int mHeight;

        public int mTileLevel;

        public int mLevelCount;

        /**
         * 同步
         */
        public volatile int mStatus = STATE_ACTIVATED;

        public TileBitmap(int x, int y, int level) {
            mX = x;
            mY = y;
            mTileLevel = level;
        }

        @Override
        public void draw(Canvas canvas, Rect source, RectF target) {
            if (mTiledBitmap != null && !mTiledBitmap.isRecycled()) {
                canvas.drawBitmap(mTiledBitmap, source, target, mPaint);
            }
        }

        @Override
        public void draw(Canvas canvas, Matrix matrix) {
            if (mTiledBitmap != null && !mTiledBitmap.isRecycled()) {
                canvas.drawBitmap(mTiledBitmap, matrix, mPaint);
            }
        }

        @Override
        public void recycle() {
            if (mTiledBitmap != null && !mTiledBitmap.isRecycled()) {
                mTiledBitmap.recycle();
            }
            mTiledBitmap = null;
        }


        public TileBitmap getParentTile() {
            if (mTileLevel + 1 == mLevelCount) return null;
            int size = TileImageView.sTileSize << (mTileLevel + 1);
            int x = size * (mX / size);
            int y = size * (mY / size);
            return getTile(x, y, mTileLevel + 1);
        }

        public void update(int x, int y, int level) {
            mX = x;
            mY = y;
            mTileLevel = level;
            recycle();
        }

        boolean decode() {
            try {
                mTiledBitmap = getTile(mTileLevel, mX, mY, sTileSize);
            } catch (Throwable t) {
            }
            return mTiledBitmap != null;
        }
    }


    private boolean isInit() {
        return mIsInit;
    }

    /**
     * 解析的线程
     */
    private class TileDecoder implements ThreadPool.Job<Void> {

        private ThreadPool.CancelListener mNotifier = new ThreadPool.CancelListener() {
            @Override
            public void onCancel() {
                synchronized (TileImageView.this) {
                    TileImageView.this.notifyAll();
                }
            }
        };

        @Override
        public Void run(ThreadPool.JobContext jc) {
            jc.setMode(ThreadPool.MODE_NONE);
            jc.setCancelListener(mNotifier);
            while (!jc.isCancelled()) {
                TileBitmap tile = null;
                synchronized (TileImageView.this) {
                    tile = mDecodeQueue.pop();
                    if (tile == null && !jc.isCancelled()) {
                        Utils.waitWithoutInterrupt(TileImageView.this);
                    }
                }
                if (tile == null) continue;
                if (decodeTile(tile)) queueForUpload(tile);
            }
            return null;
        }
    }


    /**
     * 手势处理
     */
    private class MyGestureListener implements GestureRecognizer.Listener {

        private float mTranslateX = 0.0f;
        private float mTranslateY = 0.0f;
        private boolean mIsScale = false;
        private boolean mIsDoubleTap = false;

        @Override
        public boolean onSingleTapUp(float x, float y) {
            return true;
        }

        @Override
        public boolean onSingleTapComfirm(float x, float y) {
            if (mIsDoubleTap) return false;
            if (mTapViewListener != null) {
                mTapViewListener.onViewTap(TileImageView.this, x, y);
            }
            if (!isInit()) return false;
//			if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE) return true;
            mAnimationHelper.foreFinish();
            return true;
        }

        @Override
        public boolean onDoubleTap(final float x, final float y) {
            if (!isInit()) return false;
            if (mDontNeedTile) {
                mDontNeedTile = false;
            }
//			if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE){
//				refresh();
//				return true;
//			}
            mAnimationHelper.foreFinish();
            dealDoubleTapNew(x, y);
            mIsDoubleTap = true;
            return true;
        }

        @Override
        public boolean onScroll(final float dx, final float dy, float totalX, float totalY) {//左右滑动
            if (!isInit()) return false;
            if (!mIsScale) {
//				if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE) return true;
                mAnimationHelper.foreFinish();
//				if(Math.abs(dx) >= TouchUtil.OFFSET || Math.abs(dy) >= TouchUtil.OFFSET){
                mTranslateX = -dx;
                mTranslateY = -dy;
                if (mRotation != 0) {
                    mCacheMatrix.reset();
                    mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
                    mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
                } else {
                    mCacheRect.set(mViewTargetRect);
                }
                /**
                 * 一些特殊情况的处理
                 */
                if (mCacheRect.width() <= (float) (getWidth())) {
                    mTranslateX = 0f;
                    mScrollEdge = EDGE_BOTH;
                } else {
                    mScrollEdge = EDGE_NONE;
                }

                if (mCacheRect.height() <= getHeight()) {
                    mTranslateY = 0f;
                }

                if (mCacheRect.left >= (float) (0)) {
                    if (mScrollEdge == EDGE_NONE) {
                        mScrollEdge = EDGE_LEFT;
                    }
                }
                if (mCacheRect.right <= (float) (getWidth())) {
                    if (mScrollEdge == EDGE_NONE) {
                        mScrollEdge = EDGE_RIGHT;
                    }
                }

                if (2 * Math.abs(dy) < Math.abs(dx) && isUnInterceptTouchEvent(-dx, -dy)) {//这种情况让父View获取事件
                    ViewParent parent = TileImageView.this.getParent();
                    if (null != parent)
                        parent.requestDisallowInterceptTouchEvent(false);
                    return false;
                }

                if (mTranslateX == 0f && mTranslateY == 0f) {
                } else {
                    if (mCacheRect.height() > getHeight()) {
                        if (mCacheRect.top + mTranslateY > 0f) {
                            mTranslateY = -mCacheRect.top;
                        } else if (mCacheRect.bottom + mTranslateY < getHeight()) {
                            mTranslateY = getHeight() - mCacheRect.bottom;
                        }
                    }
                    if (mCacheRect.width() > getWidth()) {
                        if (mCacheRect.left + mTranslateX > 0f) {
                            mTranslateX = -mCacheRect.left;
                        } else if (mCacheRect.right + mTranslateX < getWidth()) {
                            mTranslateX = getWidth() - mCacheRect.right;
                        }
                    }
                    if (mRotation == 90) {
                        float cache = mTranslateX;
                        mTranslateX = mTranslateY;
                        mTranslateY = -cache;
                    } else if (mRotation == 180) {
                        mTranslateX = -mTranslateX;
                        mTranslateY = -mTranslateY;
                    } else if (mRotation == 270) {
                        float cache = mTranslateX;
                        mTranslateX = -mTranslateY;
                        mTranslateY = cache;
                    }
                    mViewTargetRect.offset(mTranslateX, mTranslateY);

                    if (mRotation != 0) {
                        mCacheMatrix.reset();
                        mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
                        mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
                        setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mScale);
                    } else {
                        setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mScale);
                    }
                }
            }
//			}
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            if (!isInit()) return false;
            if (mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE) return true;
            mAnimationHelper.foreFinish();
            mAnimationHelper.fling(MIN_VALUE, MIN_VALUE, Math.round(velocityX), Math.round(velocityY), 0, MAX_VALUE, 0, MAX_VALUE);
            refresh();
            return true;
        }

        @Override
        public boolean onScaleBegin(float focusX, float focusY) {
            if (!isInit()) return false;
            if (mIsDoubleTap) return false;
//			if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE){
//				refresh();
//				return true;
//			}
            mAnimationHelper.foreFinish();
            mIsScale = true;
            return true;
        }

        @Override
        public boolean onScale(float focusX, float focusY, float scale) {
            if (!isInit()) return false;
            if (Float.isNaN(scale) || Float.isInfinite(scale)) return false;
            if (mDontNeedTile) {
                mDontNeedTile = false;
            }
//	        if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE) return false;
            dealOnScaleNew(focusX, focusY, scale);
            return true;
        }

        @Override
        public void onScaleEnd() {
            if (!isInit()) return;
            mTranslateX = 0.0f;
            mTranslateY = 0.0f;
            mIsScale = false;
        }

        @Override
        public void onDown(float x, float y) {
            if (!isInit()) return;
            mTranslateX = 0.0f;
            mTranslateY = 0.0f;
            mIsScale = false;
        }

        @Override
        public void onUp() {
            if (!isInit()) return;
            mTranslateX = 0.0f;
            mTranslateY = 0.0f;
            mIsScale = false;
            mIsDoubleTap = false;
        }

    }

    private void dealDoubleTapNew(final float x, final float y) {
        /**
         * 不能直接用等  这样会存在动画之后不能双击的BUG 需要把精度缩小  新的实现
         */
        if ((int) (mScale * AnimationHelper.SCALE_MAX / 10) == (int) (mDefaultScale * AnimationHelper.SCALE_MAX / 10)) {
            if (1 / mScale >= MAX_SCALE) {
                mCacheScale = 1;
            } else {
                mCacheScale = mScale * MAX_SCALE;
            }
            boolean flag = mFlag;
            if (isNeedRotation(mRotation)) {
                flag = !flag;
            }

            float cu[] = new float[2];
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(-mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapPoints(cu, new float[]{x, y});
            if (mViewTargetRect.contains(cu[0], cu[1])) {
                mAnimationHelper.scale(cu[0], cu[1], mScale, mCacheScale);
            } else {
                /**
                 * 旋转后中心点不会变  所以不需要 map过去
                 */
                mAnimationHelper.scale(mViewTargetRect.centerX(), mViewTargetRect.centerY(), mScale, mCacheScale);
            }
            refresh();
        } else {
            float cu[] = new float[2];
            mCacheMatrix.reset();
            /**
             * 当前点击的点是旋转后的点  所以map回去是-mRotation
             */
            mCacheMatrix.setRotate(-mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapPoints(cu, new float[]{x, y});
            if (mViewTargetRect.contains(cu[0], cu[1])) {
                mAnimationHelper.scale(cu[0], cu[1], mScale, mDefaultScale);
            } else {
                mAnimationHelper.scale(mViewTargetRect.centerX(), mViewTargetRect.centerY(), mScale, mDefaultScale);
            }
            refresh();
        }
    }

    private void dealDoubleTapOld(final float x, final float y) {
        /**
         * 不能直接用等  这样会存在动画之后不能双击的BUG 需要把精度缩小
         */
        if ((int) (mScale * AnimationHelper.SCALE_MAX / 10) == (int) (mDefaultScale * AnimationHelper.SCALE_MAX / 10)) {
            if (1 / mScale >= MAX_SCALE) {
                mCacheScale = 1;
            } else {
                mCacheScale = mScale * MAX_SCALE;
            }
            boolean flag = mFlag;
            if (isNeedRotation(mRotation)) {
                flag = !flag;
            }

            float cu[] = new float[2];
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(-mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapPoints(cu, new float[]{x, y});
//			float currentScale = mCacheScale / mDefaultScale;
            if (mViewTargetRect.contains(cu[0], cu[1])) {
//				mCacheMatrix.reset();
                if (flag) {
                    mAnimationHelper.scale(cu[0], getHeight() / 2, mScale, mCacheScale, 400);
//					mCacheMatrix.setScale(currentScale, currentScale, cu[0], getHeight() / 2);
//					mCacheMatrix.mapRect(mViewTargetRect);
                } else {
                    mAnimationHelper.scale(getWidth() / 2, cu[1], mScale, mCacheScale, 400);
//					mCacheMatrix.setScale(currentScale, currentScale, getWidth() / 2, cu[1]);
//					mCacheMatrix.mapRect(mViewTargetRect);
                }

//				if(mRotation != 0){
//					mCacheMatrix.reset();
//					mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
//					mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
//					setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mCacheScale);
//				} else{
//					setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mCacheScale);
//				}
            } else {
//				mCacheMatrix.setScale(currentScale, currentScale, getWidth() / 2, getHeight() / 2);
//				mCacheMatrix.mapRect(mViewTargetRect);
                mAnimationHelper.scale(getWidth() / 2, getHeight() / 2, mScale, mCacheScale, 400);

//				setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mCacheScale);
            }
            refresh();
        } else {
//			mCacheScale = mDefaultScale;
//			mViewTargetRect.set(mViewDefaultRect);
//			setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mCacheScale);
            mAnimationHelper.scale(getWidth() / 2, getHeight() / 2, mScale, mDefaultScale, 400);
            refresh();
        }
    }

    /**
     * 新的处理
     *
     * @param focusX
     * @param focusY
     * @param scale
     */
    private void dealOnScaleNew(float focusX, float focusY, float scale) {
        mCacheScale = mScale * scale;
        float currentScale = scale;
        if (mCacheScale <= mDefaultScale && mCacheScale >= MIN_SCALE * mDefaultScale) {
            mViewTargetRect.set(mViewDefaultRect);
            currentScale = mCacheScale / mDefaultScale;
            mCacheMatrix.reset();
            mCacheMatrix.setScale(currentScale, currentScale, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapRect(mViewTargetRect);

            setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mCacheScale);
        } else if (mCacheScale > mDefaultScale) {
            boolean flag = mFlag;
            if (isNeedRotation(mRotation)) {
                flag = !flag;
            }
            float cu[] = new float[2];
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(-mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapPoints(cu, new float[]{focusX, focusY});
            mCacheMatrix.reset();
            if (mViewTargetRect.contains(cu[0], cu[1])) {//聚焦点在当前图片显示的范围内
                mCacheMatrix.setScale(currentScale, currentScale, cu[0], cu[1]);
                mCacheMatrix.mapRect(mViewTargetRect);
                ensureRect();
            } else {//聚焦点在当前图片显示的范围外  以当前显示RectF的中心点放大  或者缩小
                mCacheMatrix.setScale(currentScale, currentScale, mViewTargetRect.centerX(), mViewTargetRect.centerY());
                mCacheMatrix.mapRect(mViewTargetRect);
                ensureRect();
            }
            if (mRotation != 0) {
                mCacheMatrix.reset();
                mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
                mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
                setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mCacheScale);
            } else {
                setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mCacheScale);
            }
        }
    }

    /**
     * 老的处理方式
     *
     * @param focusX
     * @param focusY
     * @param scale
     */
    private void dealOnScaleOld(float focusX, float focusY, float scale) {
        mCacheScale = mScale * scale;
        float currentScale = scale;
        if (mCacheScale <= mDefaultScale && mCacheScale >= MIN_SCALE * mDefaultScale) {
            mViewTargetRect.set(mViewDefaultRect);
            currentScale = mCacheScale / mDefaultScale;
            mCacheMatrix.reset();
            mCacheMatrix.setScale(currentScale, currentScale, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapRect(mViewTargetRect);

            setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mCacheScale);
        } else if (mCacheScale > mDefaultScale) {
            boolean flag = mFlag;
            if (isNeedRotation(mRotation)) {
                flag = !flag;
            }
            float cu[] = new float[2];
            mCacheMatrix.reset();
            mCacheMatrix.setRotate(-mRotation, getWidth() / 2, getHeight() / 2);
            mCacheMatrix.mapPoints(cu, new float[]{focusX, focusY});
            mCacheMatrix.reset();
            if (mViewTargetRect.contains(cu[0], cu[1])) {//聚焦点在当前图片显示的范围内
                if (flag) {
                    mCacheMatrix.setScale(currentScale, currentScale, cu[0], getHeight() / 2);
                    mCacheMatrix.mapRect(mViewTargetRect);
                } else {
                    mCacheMatrix.setScale(currentScale, currentScale, getWidth() / 2, cu[1]);
                    mCacheMatrix.mapRect(mViewTargetRect);
                }
                ensureRect();
            } else {//聚焦点在当前图片显示的范围外  以当前显示RectF的中心点放大  或者缩小
                mCacheMatrix.setScale(currentScale, currentScale, mViewTargetRect.centerX(), mViewTargetRect.centerY());
                mCacheMatrix.mapRect(mViewTargetRect);
                ensureRect();
            }
            if (mRotation != 0) {
                mCacheMatrix.reset();
                mCacheMatrix.setRotate(mRotation, getWidth() / 2, getHeight() / 2);
                mCacheMatrix.mapRect(mCacheRect, mViewTargetRect);
                setTileViewPosition(mCacheRect.centerX(), mCacheRect.centerY(), getWidth(), getHeight(), mCacheScale);
            } else {
                setTileViewPosition(mViewTargetRect.centerX(), mViewTargetRect.centerY(), getWidth(), getHeight(), mCacheScale);
            }
        }
    }

    /**
     * 计算合适的偏移量
     */
    private void ensureRect() {
        float dx = 0, dy = 0;
        if (mViewTargetRect.height() > getHeight()) {//对上下边的处理
            if (mViewTargetRect.top > 0f) {
                dy = -mViewTargetRect.top;
            } else if (mViewTargetRect.bottom < getHeight()) {
                dy = getHeight() - mViewTargetRect.bottom;
            }
        } else {//高度比View高度小  需要居中
            mViewCacheRect.set(0, 0, getWidth(), getHeight());
            dy = (mViewCacheRect.height() - mViewTargetRect.height()) / 2 + mViewCacheRect.top - mViewTargetRect.top;
        }
        if (mViewTargetRect.width() > getWidth()) {//对左右边的处理
            if (mViewTargetRect.left > 0f) {
                dx = -mViewTargetRect.left;
            } else if (mViewTargetRect.right < getWidth()) {
                dx = getWidth() - mViewTargetRect.right;
            }
        } else {//宽度比View高度小  需要居中
            mViewCacheRect.set(0, 0, getWidth(), getHeight());
            dx = (mViewCacheRect.width() - mViewTargetRect.width()) / 2 + mViewCacheRect.left - mViewTargetRect.left;
        }
        mViewTargetRect.offset(dx, dy);
    }

    /**
     * 特别注意cx cy是图片当前的RectF的中心点
     * viewW viewH是View的中心点
     * scale是当前的缩放大小
     *
     * @param cx
     * @param cy
     * @param viewW
     * @param viewH
     * @param scale
     */
    private void setTileViewPosition(float cx, float cy,
                                     int viewW, int viewH, float scale) {
        // Find out the bitmap coordinates of the center of the view
        int imageW = mImageWidth;
        int imageH = mImageHeight;
        if (isNeedRotation(mRotation)) {
            imageW = mImageHeight;
            imageH = mImageWidth;
        }
        int centerX = (int) (imageW / 2f + (viewW / 2f - cx) / scale + 0.5f);
        int centerY = (int) (imageH / 2f + (viewH / 2f - cy) / scale + 0.5f);

        int inverseX = imageW - centerX;
        int inverseY = imageH - centerY;
        int x, y;
        switch (mRotation) {
            case 0:
                x = centerX;
                y = centerY;
                break;
            case 90:
                x = centerY;
                y = inverseX;
                break;
            case 180:
                x = inverseX;
                y = inverseY;
                break;
            case 270:
                x = inverseY;
                y = centerX;
                break;
            default:
                throw new RuntimeException(String.valueOf(mRotation));
        }
        setPosition(x, y, scale, mRotation);
    }

    /**
     * centerX 和 centerY是屏幕中心Bitmap的点的坐标
     *
     * @param centerX
     * @param centerY
     * @param scale
     * @param rotation
     * @return
     */
    public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
        if (mCenterX == centerX && mCenterY == centerY
                && mScale == scale && mRotation == rotation) return false;
        mCenterX = centerX;
        mCenterY = centerY;
        mScale = scale;
        mRotation = rotation;
        layoutTiles(centerX, centerY, scale, rotation);
        return true;
    }

    private void refresh() {
        if (!mHandler.hasMessages(MSG_REFRESH)) {
            mHandler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    public void setDecodeListener(OnDecodeListener listener) {
        mDecodeListener = listener;
    }

    public void setOnViewTapListener(OnViewTapListener listener) {
        mTapViewListener = listener;
    }

    public interface OnDecodeListener {
        public void onDecodeOver(View v, boolean success);
    }

    public interface OnViewTapListener {
        public void onViewTap(View view, float x, float y);
    }


    public void resume() {
        setWillNotDraw(false);
        if (mTileDecoder == null) {
            mDontNeedTile = false;
            mTileDecoder = ((AppApplication) ComponentContext.getContext()).getThreadPool().submit(new TileDecoder());
            if (mScreen != null) {
                if (mScreen.getScreenBitmap() == null || mScreen.getScreenBitmap().isRecycled()) {
                    mScreen.reload();
                }
            }
            refresh();
        }
    }

    public void cancel() {
        if (mTileDecoder != null) {
            mDontNeedTile = true;
            mTileDecoder.cancel();
            mTileDecoder.get();
            mTileDecoder = null;
            /**
             * 重置视图
             */
            mViewTargetRect.set(mViewDefaultRect);
            setTileViewPosition(getWidth() / 2, getHeight() / 2, getWidth(), getHeight(), mDefaultScale);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!isInit()) return false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                ViewParent parent = v.getParent();
                if (null != parent)
                    parent.requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                if (mScale < mDefaultScale) {
//					if(mAnimationHelper.getMode() == AnimationHelper.MODE_SCALE){ 
//						return true;
//					}
                    mAnimationHelper.foreFinish();
                    mAnimationHelper.scale(getWidth() / 2, getHeight() / 2, mScale, mDefaultScale);
                    refresh();
                }
                break;
        }
        mGestureRecognizer.onTouchEvent(event);
        return true;
    }

    static final int EDGE_NONE = -1;
    static final int EDGE_LEFT = 0;
    static final int EDGE_RIGHT = 1;
    static final int EDGE_BOTH = 2;

    private int mScrollEdge = EDGE_BOTH;

    private boolean isUnInterceptTouchEvent(final float dx, final float dy) {
        if (mScale == mDefaultScale) {
            return true;
        }
        if (mScrollEdge == EDGE_BOTH
                || (mScrollEdge == EDGE_LEFT && dx >= 1f)
                || (mScrollEdge == EDGE_RIGHT && dx <= -1f)) {
            return true;
        }
        return false;
    }
}
